<style>
  .inline-block {
    display: inline-block;
  }
</style>

<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-if="formThead.id" v-model="listQuery.id" style="width: 200px;" class="filter-item" placeholder="id" clearable @keyup.enter.native="handleFilter"/>
      <el-input v-if="formThead.ana_record" v-model="listQuery.ana_record" style="width: 200px;" class="filter-item" placeholder="语录记录" clearable @keyup.enter.native="handleFilter"/>
      <div v-if="formThead.status" class="filter-item">
        <el-select v-model="listQuery.status" placeholder="状态" clearable @keyup.enter.native="handleFilter">
          <el-option label="启用" value="1"/>
          <el-option label="禁用" value="0"/>
        </el-select>

      </div>
      <div v-if="formThead.create_time" class="filter-item">
        <el-date-picker v-model="listQuery.create_time" type="datetime" placeholder="创建时间" clearable @keyup.enter.native="handleFilter"/>
      </div>
      <el-input v-if="formThead.classify_id" v-model="listQuery.classify_id" style="width: 200px;" class="filter-item" placeholder="语录分类" clearable @keyup.enter.native="handleFilter"/>
      <!--<div>-->
      <!--<el-form-item :label="'语录分类'" prop="classify_id">-->
      <!--<el-select v-model="formThead.classify_id" filterable placeholder="输入关键词">-->
      <!--<el-option-->
      <!--v-for="classify in classify_list"-->
      <!--:key="classify.id"-->
      <!--:label="classify.classify"-->
      <!--:value="classify.id"-->
      <!--/>-->
      <!--</el-select>-->
      <!--</el-form-item>-->
      <!--</div>-->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button v-waves class="filter-item" type="danger" icon="el-icon-delete" @click="PLdelete">批量删除</el-button>

      <div style="width: 100%;height: 35px">
        <addPage class = "inline-block margin-right-10"/>
        <batchAdd class = "inline-block margin-right-10 "/>
      </div>
    </div>

    <div class="filter-container">
      <el-checkbox v-model="formThead.id" label="id">id</el-checkbox>
      <el-checkbox v-model="formThead.ana_record" label="语录记录">语录记录</el-checkbox>
      <el-checkbox v-model="formThead.status" label="状态">状态</el-checkbox>
      <el-checkbox v-model="formThead.merchant_id" label="商家ID">商家ID</el-checkbox>
      <el-checkbox v-model="formThead.create_time" label="创建时间">创建时间</el-checkbox>
      <el-checkbox v-model="formThead.classify" label="语录分类">语录分类id</el-checkbox>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;" @selection-change="changeFun">
      <el-table-column ref="multipleTable" type="selection" width="55"/>
      <el-table-column v-if="formThead.id" label="id" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="formThead.ana_record" label="语录记录" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.ana_record }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="formThead.status" align="center" label="状态">
        <template slot-scope="scope">
          <span v-if="scope.row.status===1 "><i class="el-icon-circle-check" style="color: #67C23A"/></span>
          <span v-else><i class="el-icon-circle-close" style="color: #3574eb"/></span>
        </template>
      </el-table-column>
      <el-table-column v-if="formThead.create_time" label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.create_time | formatDate }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="formThead.classify" label="语录分类" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.classify }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--状态-->
          <el-button
            v-if="scope.row.status ===0"
            type="success"
            icon="el-icon-check"
            circle
            title="启用"
            class="buttoncss"
            @click="invoke(scope.row.id)"/>
          <el-button
            v-else-if="scope.row.status == 1"
            type="warning"
            icon="el-icon-close"
            circle
            title="禁用"
            class="buttoncss"
            @click="forbidden(scope.row.id)"/>
          <!--编辑-->
          <editPage :row_data="scope.row" @getLists="getLists"/>
          <!--删除-->
          <el-button type="danger" icon="el-icon-delete" circle @click="del(scope.row.id)"/>
        </template>
      </el-table-column>
    </el-table>
    <!--页码-->
    <div class="pagination-container">
      <el-pagination :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>
  </div>
</template>

<script>
import { getList, del, add, invoke, forbidden, add_classify, batch_delect } from '@/api/poster/ana'
import store from '@/store'
import waves from '@/directive/waves' // 水波纹指令
import addPage from './addPage'
import batchAdd from './batchAdd'
import editPage from './editPage'
import { parseTime } from '@/utils/index'
import viewAnaRecord from './viewAnaRecord'
import XLSX from 'xlsx'

export default {
  name: 'ComplexTable',
  directives: {
    waves
  },
  components: { addPage, editPage, viewAnaRecord, batchAdd },
  filters: {
    formatDate: function(time) {
      if (!time) {
        return ''
      }
      return parseTime(time)
    }
  },

  data() {
    return {
      multipleSelection: [],
      outputs: [],
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      status: [{
        value: 1,
        label: '启用'
      }, {
        value: 0,
        label: '禁用'
      }],
      listQuery: {
        id: undefined,
        ana_record: undefined,
        status: undefined,
        merchant_id: undefined,
        create_time: undefined,
        merchant_ana_id: undefined,
        classify_id: undefined,
        classify: undefined,
        page: 1,
        limit: 20
      },
      formThead: {
        id: true,
        ana_record: true,
        status: true,
        merchant_id: true,
        create_time: true,
        merchant_ana_id: true,
        classify_id: true,
        classify: true
      },
      classify_list: []
    }
  },
  created() {
    this.getLists()
  },
  methods: {
    changeFun(val) {
      console.log(val)
      this.multipleSelection = []
      val.forEach(item => {
        this.multipleSelection.push(item.id)
      })
      console.log(this.multipleSelection)
    },
    readExcel(e) {
      const that = this
      const files = e.target.files
      if (files.length < 1) {
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$toast('上传文件格式不正确，请上传xls或者xlsx格式')
        return false
      }

      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          }) // 读取数据
          const wsname = workbook.SheetNames[0] // 取第一张表
          console.log(wsname)
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) // 生成json表格内容
          // const ws1 = XLSX.utils.sheet_to_slk(workbook.Sheets[wsname]) // 输出表格对应位置是什么值
          // const ws2 = XLSX.utils.sheet_to_html(workbook.Sheets[wsname]) // 生成HTML输出
          // const ws3 = XLSX.utils.sheet_to_csv(workbook.Sheets[wsname]) // 生成分隔符分隔值输出
          // const ws4 = XLSX.utils.sheet_to_formulae(workbook.Sheets[wsname]) // 生成公式列表（具有值回退）
          // const ws5 = XLSX.utils.sheet_to_txt(workbook.Sheets[wsname]) // 生成UTF16格式的文本

          that.outputs = [] // 清空接收数据

          for (let i = 0; i < ws.length; i++) {
            if (ws[i].hasOwnProperty('语录内容') && ws[i].hasOwnProperty('语录分类')) {
              var content = ws[i]['语录内容']
              var classify = ws[i]['语录分类']
              that.outputs.push({ classify: classify, content: content })
            }
          }
          console.log('ws', ws)
          console.log('that.outputs', that.outputs)
          this.$refs.upload.value = ''
        } catch (e) {
          console.log(e)
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },
    PLdelete() {
      this.$confirm('此操作将永久删除该语录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.info('正在删除')
        batch_delect(store.getters.token, { multipleSelection: this.multipleSelection }).then(res => {
          if (res.data.status) {
            this.$message.success('已经删除')
            this.getLists()
          } else {
            this.$message.error('删除失败，原因：' + res.data.msg)
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    invoke(id) {
      invoke(store.getters.token, { id: id }).then(res => {
        this.$message({
          message: '上线成功',
          type: 'success'
        })
        this.getLists()
      })
    },
    forbidden(id) {
      forbidden(store.getters.token, { id: id }).then(res => {
        this.$message({
          message: '下线成功',
          type: 'warning'
        })
        this.getLists()
      })
    },
    getLists() {
      this.listLoading = true
      getList(store.getters.token, this.listQuery).then(response => {
        for (let i = 0; i < Object.keys(response.data.list.data).length; i++) {
          response.data.list.data[i].create_time *= 1000
        }
        this.list = response.data.list.data
        this.total = response.data.list.total
        this.listLoading = false
      })
    },
    handleSelect(key, keyPath) {
      console.log(key)
      this.listLoading = true
      this.listQuery.orderStatus = key
      getList(store.getters.token, this.listQuery).then(response => {
        this.list = response.data.list.data
        this.total = response.data.list.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getLists()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getLists()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getLists()
    },
    del(id) {
      this.$confirm('此操作将永久删除该语录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.info('正在删除，ID：' + id)
        del(store.getters.token, { id: id }).then(res => {
          if (res.status) {
            this.$message.success('已经删除，ID：' + id)
            this.getLists()
          } else {
            this.$message.error('删除失败，ID：' + res.data.msg)
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除，ID：' + id)
      })
    },
    add(id) {
      this.$confirm('添加语录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.info('正在添加，ID：' + id)
        add(store.getters.token, { id: id }).then(res => {
          if (res.status) {
            this.$message.success('已经添加，ID：' + id)
            this.getLists()
          } else {
            this.$message.error('添加失败，ID：' + id)
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除，ID：' + id)
      })
    },
    add_classify(id) {
      this.$confirm('添加语录分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.info('正在添加，ID：' + id)
        add_classify(store.getters.token, { id: id }).then(res => {
          if (res.status) {
            this.$message.success('已经添加，ID：' + id)
            this.getLists()
          } else {
            this.$message.error('添加失败，ID：' + id)
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除，ID：' + id)
      })
    }

  }
}
</script>
